import { is } from "@electron-toolkit/utils"
import { app } from "electron"
import { dirname } from "path"
import { LocalStorage } from 'node-localstorage'

export class StorageTool {

  private appUrl: string

  private folder: string

  private storageUrl: string = "/scratch"

  constructor(folder: string) {
    this.folder = folder
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.appUrl = '.'
    } else {
      // 这种写法是为了防止在打包后，路径错误，但是在开机自动启动的情况下，路径是错误的
      // appUrl = process.cwd()
      // app.getPath('exe') 获取的是exe文件的路径
      // 之所以采用这种方式，就是为了防止出现因开机自启动，导致的获取路径错误的情况
      this.appUrl = dirname(app.getPath('exe'))
    }
  }

  // 获取本地存储的值
  getStorageStr(key: string): string | null {
    const localStorage = new LocalStorage(this.appUrl + this.storageUrl + (this.folder ? `/${this.folder}` : ''))
    return localStorage.getItem(key)
  }

  setStorageStr(key: string, value: string) {
    const localStorage = new LocalStorage(this.appUrl + this.storageUrl + (this.folder ? `/${this.folder}` : ''))
    localStorage.setItem(key, value)
  }
}


